package org.hackystat.app.projectstatus.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.hackystat.core.common.project.Project;
import org.hackystat.core.common.project.ProjectManager;
import org.hackystat.core.kernel.mvc.CommandRequest;
import org.hackystat.core.kernel.mvc.Page;
import org.hackystat.core.kernel.user.User;

/**
 * Manages the updating of emails destinations added into the project specific
 * alerts.
 * 
 * @author Josh Stupplebeen
 * 
 */
public class AlertEmailManagerUpdate implements CommandRequest {

	/**
	 * Map of a project name to the list of emails which will be recieving
	 * emails.
	 */
	private Map<Project, List<String>> projectEmailMap = new HashMap<Project, List<String>>();

	/** List of valid email addresses. */
	private List<String> validProjectEmails = new ArrayList<String>();

	/** List of invalid email addresses. */
	private List<String> invalidProjectEmails = new ArrayList<String>();

	/**
	 * The process method.
	 * 
	 * @param request
	 *            the page request.
	 * @param user
	 *            The user logged in.
	 * @return The Preferences page or Error page.
	 */
	public Page process(HttpServletRequest request, User user) {

		ProjectManager manager = ProjectManager.getInstance();
		Set<Project> projectSet = manager.getProjectsWithOwner(user);
		List<String> tempValidEmailList = new ArrayList<String>();
		List<String> tempInvalidEmailList = new ArrayList<String>();

		// Initialize the project -> List<Emails> Map.
		for (Project project : projectSet) {
			this.projectEmailMap.put(project, new ArrayList<String>());
		}

		Page page = new Page("/AlertManager.jsp", "The Alert Manager");
		request.setAttribute("ProjectsOwned", projectSet);
		String emailString;
		String email;
		int y = 0;

		for (Project project : projectSet) {
			emailString = request.getParameter("emails" + String.valueOf(y));
      System.out.println("emailString = " + emailString);
			StringTokenizer st = new StringTokenizer(emailString, ", ");
			if ((emailString != null) || (emailString != "")) {
				while (st.hasMoreTokens()) {
					email = st.nextToken();
          System.out.println("email = " + email);
					// Validate the email address here
					if (validateEmail(email)) {
						this.projectEmailMap.get(project).add(email);
						tempValidEmailList.add(email);
						this.validProjectEmails.add(email);
					} else {
						this.invalidProjectEmails.add(email);
						tempInvalidEmailList.add(email);
					}
				}
			} else {
				System.out.println("request parameter returned null");
			}
			y++;
		}

		System.out.println("-- State of the Project Map --");
		Iterator i = this.projectEmailMap.entrySet().iterator();
		while (i.hasNext()) {
			Map.Entry pairs = (Map.Entry) i.next();
			System.out.println(pairs.getKey() + " = " + pairs.getValue());
			Project p = (Project) pairs.getKey();
			List<String> l = this.projectEmailMap.get(p);
      System.out.println("    -- " + p.getName() + " Emails --");
			for (String string : l) {
				System.out.println(string);
			}
		}

		if (!this.invalidProjectEmails.isEmpty()) {
			request.setAttribute("InvalidEmailFeedback",
					"The following INVALID emails were entered");
			request.setAttribute("InvalidEmailList", tempInvalidEmailList);
		}
		if (!this.validProjectEmails.isEmpty()) {
			request.setAttribute("ValidEmailFeedback",
					"The following emails have been updated");
			request.setAttribute("ValidEmailList", tempValidEmailList);
			request.setAttribute("EmailList", this.projectEmailMap);
		}
		if (this.validProjectEmails.isEmpty()
				&& this.invalidProjectEmails.isEmpty()) {
			request
					.setAttribute("ValidEmailFeedback",
							"No emails were entered");
		}

		return page;
	}

	/**
	 * Getter for the project->emailString map.
	 * 
	 * @return The Project->emailString map.
	 */
	public Map<Project, List<String>> getEmailMap() {
		return this.projectEmailMap;
	}

	/**
	 * Getter for the valid email List.
	 * 
	 * @return A List<String> containing validated email strings.
	 */
	public List<String> getValidProjectEmails() {
		return this.validProjectEmails;
	}

	/**
	 * Getter for the invalid email List.
	 * 
	 * @return A List<String> containing invalid email strings.
	 */
	public List<String> getInvalidProjectEmails() {
		return this.invalidProjectEmails;
	}

	/**
	 * Attempts to validate the email entered using regular expressions. Code
	 * taken from:
	 * http://java.sun.com/developer/technicalArticles/releases/1.4regex/
	 * 
	 * @param email
	 *            The email address.
	 * @return Returns a boolean indicating whether the email entered is valid
	 *         or not.
	 */
	public boolean validateEmail(String email) {
		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
		Matcher m = p.matcher(email);
		boolean matchFound = m.matches();

		if (matchFound & email != null && (email = email.trim()).length() > 0) {
			return true;
		} else {
			return false;
		}
	}

}
